﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting;
using System.Reflection;
using Swashbuckle.AspNetCore.SwaggerGen;
using WebApiCore.Extension;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Swashbuckle.AspNetCore.Filters;
using Microsoft.Extensions.Options;
using WebApiCore.Setting;
using WebApiCore.Helper;

namespace WebApiCore.Extension
{
    public static class SwaggerExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwagger(this IApplicationBuilder app, Assembly assembly)
        {
            // 读swagger配置
            //var builder = new ConfigurationBuilder().AddJsonFile(@"Config/swagger.json");
            //var configuration = builder.Build();

			swaggerSetting swaggerSetting = App.GetOptions<swaggerSetting>();

			app.UseSwagger(c =>
            {
            });
            app.UseSwaggerUI(c =>
            {
                var customIndex = $"{Assembly.GetExecutingAssembly().GetName().Name}.html.index.html";
                c.IndexStream = (Func<Stream>)(() => Assembly.GetExecutingAssembly().GetManifestResourceStream(customIndex));
                c.RoutePrefix = string.Empty;
                c.SwaggerEndpoint("/swagger/v1/swagger.json", swaggerSetting.Title + " " + swaggerSetting.Version);

            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddSwaggerConfig(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            // 读swagger配置
            var builder = new ConfigurationBuilder().AddJsonFile(@"Config/swagger.json");
            var configuration = builder.Build();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(configuration["Version"], new OpenApiInfo
                {
                    Title = configuration["Title"],
                    Version = configuration["Version"],
                    Description = configuration["Description"],
                });

                string FileDirectory = AppDomain.CurrentDomain.BaseDirectory;   // 获取基目录

                IncludeXmlComments(c, FileDirectory, AppDomain.CurrentDomain.FriendlyName + ".xml"); // 增加当前工程swagger文档

				var assembly = AssemblyUtils.GetAssemblies().ToList();
				foreach (var an in assembly)
				{
                    
                    
					if (!an.GetName().Name.Contains("System") &&
						!an.GetName().Name.Contains("mscorlib") && !an.GetName().Name.Contains("Microsoft"))
					{
						IncludeXmlComments(c, FileDirectory, an.GetName().Name + ".xml");
					}
				}

				// 添加引用的所有程序集swagger文档
				Assembly assem = Assembly.GetEntryAssembly();
                foreach (AssemblyName an in assem.GetReferencedAssemblies())
                {
                    if (!an.Name.Contains("System") &&
                        !an.Name.Contains("mscorlib") && !an.Name.Contains("Microsoft"))
                    {
                        IncludeXmlComments(c, FileDirectory, an.Name + ".xml");
                    }
                }

                //参考文章：http://www.zyiz.net/tech/detail-134965.html
                //需要安装包Swashbuckle.AspNetCore.Filters
                // 开启权限小锁 需要在对应的Action上添加[Authorize]才能看到
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                //在header 中添加token，传递到后台
                c.OperationFilter<SecurityRequirementsOperationFilter>();
                c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme,
                    new OpenApiSecurityScheme
                    {
                        In = ParameterLocation.Header,
                        Description = "请输入Login接口返回的Token，前置Bearer。示例：Bearer {Token}",
                        Name = "Authorization",//jwt默认的参数名称,
                        Type = SecuritySchemeType.ApiKey, //指定ApiKey
                        BearerFormat = "JWT",//标识承载令牌的格式 该信息主要是出于文档目的
                        Scheme = JwtBearerDefaults.AuthenticationScheme//授权中要使用的HTTP授权方案的名称
                    });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                        },
                        new List<string>()
                    }
                });
            });
        }

        /// <summary>
        /// 加载指定swagger文档
        /// </summary>
        /// <param name="c"></param>
        /// <param name="FileDirectory">文件目录</param>
        /// <param name="Name">文件名</param>
        private static void IncludeXmlComments(SwaggerGenOptions c, string FileDirectory, string Name)
        {
            try
            {
                c.IncludeXmlComments(Path.Combine(FileDirectory, Name), true); // 增加swagger文档
            }
            catch (Exception ex)
            {
                Console.WriteLine("swagger 文档加载失败" + ex.Message);
            }
        }
    }
}
